package space

import (
	"path"
	"src/zeus/common"
	"src/zeus/pathfinder"

	// "src/zeus/unitypx"
	"sync"

	"src/zeus/logger"
)

// Maps 地图信息集合
type Maps struct {
	sync.RWMutex
	loadedMap  map[string]*MapTask
	pendingMap map[string]*MapTask
}

var mapsInst *Maps
var once sync.Once

func getMapsInst() *Maps {
	once.Do(func() {
		mapsInst = &Maps{
			loadedMap:  make(map[string]*MapTask),
			pendingMap: make(map[string]*MapTask),
		}
	})
	return mapsInst
}

func (ms *Maps) GetMap(mapName string, loadObstacle int32) *MapTask {

	if loadObstacle == 0 {
		task, ok := ms.getMap(mapName)
		if !ok {
			task = ms.getMapTry(mapName)
		}
		return task
	} else {
		// 每次都分配独立的地图
		task := newMapTask(mapName)
		ms.loadMapObstacle(task)
		return task
	}
}

func (ms *Maps) getMap(mapName string) (task *MapTask, ok bool) {
	ms.RLock()
	defer ms.RUnlock()
	task, ok = ms.loadedMap[mapName]
	return
}

func (ms *Maps) getMapTry(mapName string) *MapTask {
	ms.Lock()
	defer ms.Unlock()
	task, ok := ms.loadedMap[mapName]
	if ok {
		return task
	}
	task = newMapTask(mapName)
	task.info.LoadObstacle = 0
	ms.loadMap(task)
	return task
}

func (ms *Maps) loadMap(task *MapTask) {
	levelPath := path.Join(common.GetResPath(), "maps", task.name)
	cgo_navmesh := pathfinder.GetNavMesh(path.Join(levelPath, "level.bin"))

	//此处才是真正加载navmesh的地方
	if cgo_navmesh == nil {
		logger.Error(" load cgonavmesh failed ")
	}

	mapInfo := newMap()
	mapInfo.Cgo_navmesh = cgo_navmesh
	task.info = mapInfo
	ms.loadedMap[task.name] = task

}

func (ms *Maps) loadMapObstacle(task *MapTask) {
	levelPath := path.Join(common.GetResPath(), "maps", task.name)
	cgo_tonavmesh := pathfinder.GetNavMeshTO(path.Join(levelPath, "level.bin.to"))
	if cgo_tonavmesh == nil {
		logger.Error("[loadMapObstacle] GetNavMeshTO load cgo_tonavmesh failed")
	}
	mapInfo := newMap()
	mapInfo.LoadObstacle = 1
	mapInfo.Cgo_TONavmesh = cgo_tonavmesh
	task.info = mapInfo
}

// MapTask 地图任务
type MapTask struct {
	name string
	info *Map
}

func newMapTask(name string) *MapTask {
	return &MapTask{
		name: name,
		info: &Map{},
	}
}

// Map 单独的地图信息
type Map struct {
	LoadObstacle  int32
	Cgo_navmesh   *pathfinder.Cgo_dtNavMesh
	Cgo_TONavmesh *pathfinder.Cgo_TempObstaclesNavMesh
}

//func(this* Map) OnDestroy(){
//
//}

func newMap() *Map {
	return &Map{}
}
